<template>
    <div class="app-container page-wood-purchase-in">
        <el-row :gutter="10" class="sumbit-btn-group mb8">
            <el-col class="flex-center" :span="1.5">
                <SearchInput
                    v-model="postParams.orderId"
                    :api="$Api.woodPurchase.order.list"
                    :params="{ pageNum: 1, pageSize: 10, auditStatus: 1 }"
                    searchKey="pactNum"
                    selectLabel="orderId"
                    placeholder="输入或查询合同号"
                    @change="searchInputChange"
                    :disabled="disabled"
                    :all="false"
                />
                <span class="sub-text">必须存在订单号才可以进行后续操作</span>
            </el-col>
            <div class="empty"></div>
            <!-- 新增时的按钮组 -->
            <template v-if="!inId">
                <el-col :span="1.5">
                    <el-button
                        type="primary"
                        plain
                        icon="el-icon-plus"
                        size="mini"
                        v-hasPermi="['woodPurchase:woodPurchaseIn:add']"
                        @click="savePurchase(1)"
                        >保存并新增</el-button
                    >
                </el-col>
                <el-col :span="1.5">
                    <el-button
                        type="success"
                        plain
                        icon="el-icon-edit"
                        size="mini"
                        v-hasPermi="['woodPurchase:woodPurchaseIn:add']"
                        @click="savePurchase(0)"
                        >保存</el-button
                    >
                </el-col>
                <el-col :span="1.5">
                    <Import
                        :api="$Api.woodPurchase.in.import"
                        @success="importSuccess"
                    />
                </el-col>
            </template>

            <!-- 编辑时的按钮组 -->
            <template v-else>
                <el-button
                    type="primary"
                    plain
                    icon="el-icon-plus"
                    size="mini"
                    v-hasPermi="['woodPurchase:woodPurchaseIn:add']"
                    @click="clearParams(1)"
                    >新增</el-button
                >
                <el-col :span="1.5">
                    <el-button
                        type="success"
                        plain
                        icon="el-icon-edit"
                        size="mini"
                        v-hasPermi="['woodPurchase:woodPurchaseIn:add']"
                        @click="savePurchase(0)"
                        :disabled="disabled"
                        >保存</el-button
                    >
                </el-col>

                <el-col :span="1.5">
                    <el-button
                        type="success"
                        size="mini"
                        @click="setAuditStatus"
                        >{{
                            postParams.auditStatus == 1 ? "反审核" : "审核"
                        }}</el-button
                    >
                </el-col>
            </template>
        </el-row>

        <div class="table-area">
            <el-form
                :model="postParams"
                :inline="true"
                ref="form"
                label-width="90px"
                :rules="rules"
            >
                <el-form-item label="供应商" prop="supplierName">
                    <SupplierSelect
                        v-model="postParams.supplierName"
                        placeholder="请输入供应商"
                        :disabled="disabled"
                    />
                </el-form-item>
                <el-form-item label="提单号" prop="ladingNum">
                    <el-input
                        v-model="postParams.ladingNum"
                        placeholder="请输入提单号"
                        clearable
                        size="small"
                        @keyup.enter.native="handleQuery"
                        :disabled="disabled"
                    />
                </el-form-item>
                <el-form-item label="到港日期" prop="arriveTime">
                    <el-date-picker
                        clearable
                        size="small"
                        v-model="postParams.arriveTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="选择到港日期"
                        :disabled="disabled"
                    >
                    </el-date-picker>
                </el-form-item>

                <el-form-item label="港口" prop="harbor">
                    <el-select
                        v-model="postParams.harbor"
                        placeholder="请选择港口"
                        :disabled="disabled"
                    >
                        <el-option
                            v-for="item in select.woodPort"
                            :key="item.value"
                            :label="item.basicsName"
                            :value="item.basicsName"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="批次号" prop="batchNum">
                    <el-input
                        v-model="postParams.batchNum"
                        clearable
                        size="small"
                        placeholder="请输入批次号"
                        :disabled="disabled"
                    />
                </el-form-item>
                <el-form-item label="开证合同" prop="pactNum">
                    <el-input
                        v-model="postParams.pactNum"
                        clearable
                        size="small"
                        placeholder="请输入开证合同"
                        :disabled="disabled"
                    />
                </el-form-item>
                <el-form-item label="柜数:" prop="caseCount">
                    <el-input-number
                        style="width: 215px"
                        v-model="postParams.caseCount"
                        placeholder="为空时,系统将自动统计"
                        clearable
                        size="small"
                        :disabled="disabled"
                    />
                </el-form-item>
                <el-form-item label="装运日期" prop="shippingTime">
                    <el-date-picker
                        clearable
                        size="small"
                        v-model="postParams.shippingTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="选择装运日期"
                        :disabled="disabled"
                    >
                    </el-date-picker>
                </el-form-item>

                <el-form-item label="总金额" prop="money">
                    <el-input
                        v-model="postParams.money"
                        clearable
                        size="small"
                        :placeholder="totalMoney"
                        :class="{ error: totalMoney != postParams.money }"
                        :disabled="disabled"
                    />
                </el-form-item>
                <el-form-item label="币别:" prop="currency">
                    <el-select
                        v-model="postParams.currency"
                        size="small"
                        :disabled="disabled"
                    >
                        <el-option label="RMB" value="RMB" />
                        <el-option label="USD" value="USD" />
                        <el-option label="EUR" value="EUR" />
                    </el-select>
                </el-form-item>

                <!-- 表格开始 -->
                <TableForm
                    ref="TableForm"
                    :list="postParams.woodPurchaseInGoodsList"
                    :column="tableFormRender"
                    :summary="true"
                    :loading="loading"
                    :disabled="disabled"
                />
                <!-- 表格结束 -->

                <!-- 备注信息 -->
                <el-form-item class="form-remark" prop="remark">
                    <el-input
                        type="textarea"
                        placeholder="请输入备注信息"
                        v-model="postParams.remark"
                        clearable
                        size="small"
                        rows="4"
                        :disabled="disabled"
                    />
                </el-form-item>

                <img
                    v-if="showAuditStatus && postParams.auditStatus == 1"
                    :src="img.audit"
                    class="img-audit"
                />
            </el-form>
        </div>

        <!-- 添加或修改采购入库信息对话框 -->
        <el-dialog
            title="全部入库"
            :visible.sync="showAuditDialog"
            width="600px"
            :before-close="handleCloseAuditDialog"
            class="modal-audit"
            :close-on-click-modal="false"
        >
            <p>
                <b>已生成在途库存，是否全部入库？</b>
            </p>
            <p>
                <span>若全部入库，请选择入库日期：</span>
                <el-date-picker
                    v-model="purchaseInDate"
                    type="date"
                    placeholder="选择日期"
                >
                </el-date-picker>
            </p>
            <p>
                <span>若分批入库请前往</span>
                <span class="link" @click="pageGoBinPartial">箱柜分批入库</span>
                <span>继续操作</span>
            </p>
            <span slot="footer" class="dialog-footer">
                <el-button @click="showAuditDialog = false">取 消</el-button>
                <el-button type="primary" @click="auditDialogAllIn"
                    >确 定</el-button
                >
            </span>
        </el-dialog>
    </div>
</template>

<script>
import TableForm from "@/components/TableForm/preset";
import SupplierSelect from "@/components/SupplierSelect";
import SearchInput from "@/components/SearchInput";

export default {
    name: "WoodPurchaseIn",
    components: {
        TableForm,
        SupplierSelect,
        SearchInput,
    },
    data() {
        return {
            inId: "",
            // 遮罩层
            loading: false,
            // 查询参数
            postParams: {
                orderId: "",
                currency: "RMB",
                money: "",
                auditStatus: 0,
                // 采购入库信息表格数据
                woodPurchaseInGoodsList: [
                    {
                        baleNum: "", // 包号
                        goodsName: "", // 商品名称
                        brandName: "", // 品牌名称
                        level: "", // 等级
                        warehouse: "", // 仓位
                        storageLocation: "", // 库位
                        ply: 0, // 厚度
                        width: 0, // 宽度
                        length: 0, // 长度
                        sliceCount: 0, // 片数
                        pieceCount: 0, // 件数
                        oneCount: 0, // 单包方数
                        inCount: 0, // 方数
                        oneNoteCount: "", // 单包码单
                        noteCount: "", // 码单
                        price: "", // 单价
                        money: "", // 金额
                        caseNum: "", // 箱号
                        goodsState: "", // 货物状态
                        originPlace: "", // 产地
                        sourceOrder: "", // 源单号
                        remark: "", // 备注
                    },
                ],
            },
            // 各选择框数据
            select: {
                goodsName: [],
                productName: [],
                levelName: [],
                warehouseName: [],
                woodPort: [],
            },
            img: {
                audit: require("@/assets/images/bg@audit.png"),
            },
            rules: {
                ladingNum: [
                    {
                        required: true,
                        message: "提单号不能为空",
                        trigger: "blur",
                    },
                ],
                supplierName: [
                    {
                        required: true,
                        message: "请选择供应商",
                        trigger: "blur",
                    },
                ],
                arriveTime: [
                    {
                        required: true,
                        message: "请选择到港日期",
                        trigger: "blur",
                    },
                ],
            },
            tableFormRender: [
                { label: "包号" },
                { label: "品名" },
                { label: "品牌(批量)" },
                { label: "等级(批量)" },
                { label: "仓库(批量)" },
                { label: "库位(批量)" },
                { label: "厚度(mm)" },
                { label: "宽度(mm)" },
                { label: "长度(m)" },
                { label: "片数" },
                { label: "件数" },
                { label: "单包方数" },
                { label: "方数" },
                { label: "单包码单" },
                { label: "码单" },
                { label: "单价(批量)" },
                { label: "金额" },
                { label: "箱号(批量)" },
                { label: "货物状态(批量)" },
                { label: "产地(批量)" },
                { label: "源单序号" },
                { label: "备注(批量)" },
            ],
            showAuditStatus: false,
            showAuditDialog: false,
            purchaseInDate: "",
        };
    },
    created() {
        let { id } = this.$route.params;
        let { orderId } = this.$route.query;

        if (orderId) {
            this.postParams.orderId = orderId;
            this.getPurchaseInDetailByOrderId(orderId);
        } else if (id) {
            this.inId = id;
            id && this.getPurchaseInDetail();
        }
    },
    computed: {
        disabled() {
            return this.postParams.auditStatus == 1;
        },
        totalMoney() {
            let { woodPurchaseInGoodsList } = this.postParams;
            let sum = 0;
            woodPurchaseInGoodsList.forEach((v) => {
                sum += Number(v.money);
            });

            this.postParams.money = sum;
            return sum.toFixed(3);
        },
    },
    methods: {
        // 审核弹窗
        auditDialogAllIn() {
            let { purchaseInDate } = this;
            let { orderId, woodPurchaseInGoodsList } = this.postParams;
            let ids = [];

            woodPurchaseInGoodsList.forEach((v) => {
                ids.push(v.itemId);
            });

            if (!purchaseInDate) {
                this.$message.error("若全部入库，请选择入库日期");
                return false;
            }

            this.$Api.woodPurchase.bin
                .setState({
                    ids,
                    type: 1,
                    inTime: purchaseInDate,
                    orderId,
                })
                .then((res) => {
                    this.showAuditDialog = false;
                    this.$message.success("操作成功");
                });
        },
        pageGoBinPartial() {
            this.$router.push({
                path: "/purchase/invoice/bin-partial",
            });
        },
        // 审核与反审核
        setAuditStatus() {
            let { inId } = this;
            let { auditStatus } = this.postParams;
            let nextAudit = auditStatus == 1 ? 0 : 1;
            this.$Api.woodPurchase.in
                .Audit({
                    auditStatus: nextAudit,
                    arrayInIds: [inId],
                })
                .then((res) => {
                    this.$message.success(res.msg);
                    this.postParams.auditStatus = nextAudit;
                    !!nextAudit && (this.showAuditDialog = true);
                });
        },
        // 获取详情
        getPurchaseInDetail() {
            let { inId } = this;
            this.$Api.woodPurchase.in.detail(inId).then((res) => {
                let { data, code } = res;
                if (code === 200) {
                    this.postParams = data;
                    this.showAuditStatus = !!data.ladingNum;
                }
            });
        },
        // 根据orderId获取详情
        getPurchaseInDetailByOrderId(orderId) {
            if (this.loading) return false;
            this.loading = true;

            this.$Api.woodPurchase.order
                .detail(orderId)
                .then((res) => {
                    this.loading = false;
                    let { data, code } = res;
                    if (code === 200) {
                        data.woodPurchaseInGoodsList =
                            data.woodPurchaseOrderGoodsList;
                        delete data.woodPurchaseOrderGoodsList;
                        data.auditStatus = 0;
                        data.ladingNum = "";
                        this.postParams = data;
                    }
                })
                .catch(() => {
                    this.loading = false;
                });
        },
        searchInputChange(orderId) {
            this.getPurchaseInDetailByOrderId(orderId);
        },
        handleCloseAuditDialog() {
            this.showAuditDialog = false;
        },
        // 保存采购入库信息
        savePurchase(clear = false) {
            let { postParams, totalMoney, loading, inId } = this;

            if (loading) return;

            if (!postParams.orderId) {
                this.msgError("必须存在订单号才可以进行后续操作");
                return false;
            }

            this.$refs["form"].validate((pass, error) => {
                pass &&
                    this.$refs["TableForm"].checkForm(
                        (tableFormPass, error) => {
                            if (tableFormPass) {
                                this.loading = true;
                                !postParams.money &&
                                    (postParams.money = totalMoney);
                                let params = postParams;
                                this.$Api.woodPurchase.in
                                    .save(params)
                                    .then((res) => {
                                        let { code, data } = res;
                                        setTimeout(() => {
                                            this.loading = false;
                                            this.inId = data;
                                            this.$message({
                                                message: inId
                                                    ? "保存成功"
                                                    : "新增成功",
                                                type: "success",
                                            });
                                            code === 200 &&
                                                clear &&
                                                this.clearParams();
                                        }, 1200);
                                    })
                                    .catch(() => {
                                        this.loading = false;
                                    });
                            }
                        }
                    );
            });
        },
        // 清除参数
        clearParams() {
            this.inId = "";
            this.postParams = {
                currency: "RMB",
                money: "",
                woodPurchaseInGoodsList: [
                    {
                        baleNum: "", // 包号
                        goodsName: "", // 商品名称
                        brandName: "", // 品牌名称
                        level: "", // 等级
                        warehouse: "", // 仓位
                        storageLocation: "", // 库位
                        ply: 0, // 厚度
                        width: 0, // 宽度
                        length: 0, // 长度
                        sliceCount: 0, // 片数
                        pieceCount: 0, // 件数
                        oneCount: 0, // 单包方数
                        inCount: 0, // 方数
                        oneNoteCount: "", // 单包码单
                        noteCount: "", // 码单
                        price: "", // 单价
                        money: "", // 金额
                        caseNum: "", // 箱号
                        goodsState: "", // 货物状态
                        originPlace: "", // 产地
                        sourceOrder: "", // 源单号
                        remark: "", // 备注
                    },
                ],
            };
        },
        importSuccess(res) {
            let { data } = res;
            if (data) {
                data.woodPurchaseInGoodsList = data.woodPurchaseInExcels;
                data.ladingNum = "";
                delete data.woodPurchaseInExcels;
                this.postParams = data;
            }
        },
    },
};
</script>

<style lang="scss" scoped>
::v-deep.page-wood-purchase-in {
    .sub-text {
        margin-left: 20px;
        font-size: 12px;
        color: #b7b7b7;
        user-select: none;
    }
    .table-area {
        .img-audit {
            position: absolute;
            right: 30px;
            bottom: 30px;
            transform: rotate(-18deg);
            pointer-events: none;
        }
    }
    .el-input.is-disabled .el-input__inner,
    .el-textarea.is-disabled .el-textarea__inner {
        background: #f5f5f5;
        cursor: inherit;
        color: #999;
    }

    .el-input-number__increase,
    .el-input-number__decrease {
        background: #fff;
    }

    .sumbit-btn-group {
        position: relative;
        z-index: 100;
        margin: 10px 0 20px 0;
        display: flex;
        align-items: center;
        justify-content: space-between;
        .empty {
            width: 100%;
            flex: 1;
        }
    }

    .error {
        color: #fa3e3e !important;
        input {
            color: #fa3e3e !important;
        }
    }

    .form-remark {
        display: block;
        display: block;
        margin: 20px 15px 15px;
        .el-form-item__content {
            width: 100%;
        }
    }

    .modal-audit {
        .link {
            display: inline-block;
            margin: 0 10px;
            cursor: pointer;
            color: #1890ff;
            text-decoration: underline;
        }
    }
}
</style>